#include "TcpConnection.h"
#include "EventLoopThread.h"
#include "CountDownLatch.h"
#include "TcpClient.h"
#include <iostream>
#include <string>
#include <functional>

using namespace std;

class TranslateClient
{
public:
    TranslateClient(const string &svr_ip, int svr_port)
        : _latch(1), _client(_loopthread.startLoop(), muduo::net::InetAddress(svr_ip, svr_port), "TranslateClient")
    {
        // 参数绑定回调
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void connect()
    {
        _client.connect(); // 连接服务器
        _latch.wait();     // 主线程进入阻塞，等待连接成功后，调用onConnection回调唤醒
    }
    bool send(const string &msg)
    {
        if (_server_conn->connected()) // 检测连接状态正常
        {
            _server_conn->send(msg); // 通过连接发送
            return true;
        }
        return false;
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    { // 成功连接服务器时回调
        if (conn->connected())
        {
            _latch.countDown(); // 唤醒主线程的阻塞
            _server_conn = conn;
        }
        else
        {
            // 连接关闭
            _server_conn.reset(); // 重置连接
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    { // 获取到消息时回调
        cout << "result:" << buf->retrieveAllAsString() << endl;
    }

private:
    muduo::CountDownLatch _latch;              // 防止连接还没建立成功，就使用未定义的连接对象
    muduo::net::EventLoopThread _loopthread;   // 客户端也需要事件监控，但不能像服务器那样死循环阻塞监控，而是创建线程监控，创建成功后自动开启循环监控
    muduo::net::TcpClient _client;             // 客户端类
    muduo::net::TcpConnectionPtr _server_conn; // 服务器连接对象
};

int main()
{
    TranslateClient client("127.0.0.1", 8080);
    client.connect();
    while (true)
    {
        string msg;
        cin >> msg;
        client.send(msg);
    }
    return 0;
}